package org.ifi.p17.ccolor;

import com.buzzingandroid.ui.HSVColorPickerDialog;
import com.buzzingandroid.ui.HSVColorPickerDialog.OnColorSelectedListener;

import java.util.List;

import org.opencv.android.OpenCVLoader;
import org.opencv.android.Utils;
import org.opencv.core.Core;
import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.MatOfPoint;
import org.opencv.core.Point;
import org.opencv.core.Rect;
import org.opencv.core.Scalar;
import org.opencv.core.Size;
import org.opencv.imgproc.Imgproc;

import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class ColorActivity extends Activity implements OnTouchListener{
	private static final String  TAG = "Color::Activity";
	private static final int SELECT_PICTURE = 1;
	private String imagePath;
	
	private Mat mImage;
	private Mat mChangedImage;
	private Bitmap mBitmap;
	private Scalar mBlobColorHsv;
	private Scalar mBlobColorRgba;
	private Point mPoint;
	
    private ColorDectector mDetector;
    private Mat mSpectrum = new Mat();
    private Size SPECTRUM_SIZE = new Size(200, 60);
    private Scalar CONTOUR_COLOR = new Scalar(255,0,0,255);
    
    ImageView mImageView;
    
	static {
	    if (!OpenCVLoader.initDebug()) {
	        // Handle initialization error
	    }
	}
	
    public ColorActivity() {
        Log.i(TAG, "Instantiated new " + this.getClass());
    }
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		String imagePath = "/sdcard/Pictures/100075.jpg";
		setContentView(R.layout.activity_color);
		mImageView = (ImageView) findViewById(R.id.mainImageView);		
/**
		((Button) findViewById(R.id.browseGallery)).setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent,"Select Picture"), SELECT_PICTURE);
            }
        });
*/        
		
/*		
		mBitmap = BitmapFactory.decodeFile(imagePath);
				
		//Mat img = Highgui.imread("/sdcard/Pictures/100075.jpg");
		mImage = new Mat();
		mChangedImage = new Mat();
		Utils.bitmapToMat(mBitmap, mImage);
//		img.inv();
		Utils.matToBitmap(mImage, mBitmap);
		mImageView.setImageBitmap(mBitmap);
*/		
		mImageView.setOnTouchListener(this);
		mDetector = new ColorDectector();
		mPoint = new Point(0, 0);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.color, menu);
		return true;
	}

	@Override
	  public boolean onOptionsItemSelected(MenuItem item) {
	    switch (item.getItemId()) {
	    case R.id.action_browse:
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent,"Select Picture"), SELECT_PICTURE);
	      break;
	    case R.id.action_settings:
	    	HSVColorPickerDialog cpd = new HSVColorPickerDialog( this, 0xFF4488CC, new OnColorSelectedListener() {
	    	    @Override
	    	    public void colorSelected(Integer color) {
	    	        // Do something with the selected color
	    	    	Toast.makeText(ColorActivity.this, "Menu item 2 selected", Toast.LENGTH_SHORT).show();
	    	    }
	    	});
	    	cpd.setTitle( "Pick a color" );
	    	cpd.show();	    		      
	      break;
	    default:
	      break;
	    }

	    return true;
	  } 	
	
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            if (requestCode == SELECT_PICTURE) {
                Uri selectedImageUri = data.getData();
                imagePath = getPath(selectedImageUri);
System.out.println("Image Path : " + imagePath);
                //mImageView.setImageURI(selectedImageUri);
		
        		mBitmap = BitmapFactory.decodeFile(imagePath);
        				
        		//Mat img = Highgui.imread("/sdcard/Pictures/100075.jpg");
        		mImage = new Mat();
        		mChangedImage = new Mat();
        		Utils.bitmapToMat(mBitmap, mImage);
//        		img.inv();
        		Utils.matToBitmap(mImage, mBitmap);
        		mImageView.setImageBitmap(mBitmap);
                
            }
        }
    }
 
    public String getPath(Uri uri) {
        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = managedQuery(uri, projection, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }	
	
	private Mat loadImage(){
		return null;
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		int rows = mImage.rows();
		int cols = mImage.cols();
		if (event.getAction() == MotionEvent.ACTION_DOWN) {
			mPoint.x = event.getX();
			mPoint.y = event.getY();
			Log.i(TAG, "DOWN");
		}
		
		Log.i(TAG, "Touch point : x = " + mPoint.x + "y = " + mPoint.y);
		if( mPoint.x < cols && mPoint.y < rows){
			int x = (int)mPoint.x;
			int y = (int)mPoint.y;
			//process here
			Rect touchedRect = new Rect();
			touchedRect.x = (x>4) ? x-4 : 0;
			touchedRect.y = (y>4) ? y-4 : 0;

			touchedRect.width = (x+4 < cols) ? x + 4 - touchedRect.x : cols - touchedRect.x;
			touchedRect.height = (y+4 < rows) ? y + 4 - touchedRect.y : rows - touchedRect.y;
			
			Mat touchedRegionRgba = mImage.submat(touchedRect);

	        Mat touchedRegionHsv = new Mat();
	        Imgproc.cvtColor(touchedRegionRgba, touchedRegionHsv, Imgproc.COLOR_RGB2HSV_FULL);
	        
		       // Calculate average color of touched region
	        mBlobColorHsv = Core.sumElems(touchedRegionHsv);
	        int pointCount = touchedRect.width*touchedRect.height;
	        for (int i = 0; i < mBlobColorHsv.val.length; i++)
	            mBlobColorHsv.val[i] /= pointCount;

	        mBlobColorRgba = converScalarHsv2Rgba(mBlobColorHsv);

	        Log.i(TAG, "Touched rgba color: (" + mBlobColorRgba.val[0] + ", " + mBlobColorRgba.val[1] +
	                ", " + mBlobColorRgba.val[2] + ", " + mBlobColorRgba.val[3] + ")");

	        mDetector.setColorHsv(mBlobColorHsv);

	        Imgproc.resize(mDetector.getSpectrum(), mSpectrum, SPECTRUM_SIZE);

            //mDetector.process(mImage);
            
	        mChangedImage = mDetector.replaceColor(mImage);
	        
            //List<MatOfPoint> contours = mDetector.getContours();
            //Log.e(TAG, "Contours count: " + contours.size());
            //Imgproc.drawContours(mImage, contours, -1, CONTOUR_COLOR);            
            //mImageView.setImageBitmap(Utils.matToBitmap(mImage, bmp));
	        //mIsColorSelected = true;
	        
            Utils.matToBitmap(mChangedImage, mBitmap);
            mImageView.setImageBitmap(mBitmap);
	        touchedRegionRgba.release();
	        touchedRegionHsv.release();

		}
		// TODO Auto-generated method stub
		return false;
	}
	   private Scalar converScalarHsv2Rgba(Scalar hsvColor) {
	        Mat pointMatRgba = new Mat();
	        Mat pointMatHsv = new Mat(1, 1, CvType.CV_8UC3, hsvColor);
	        Imgproc.cvtColor(pointMatHsv, pointMatRgba, Imgproc.COLOR_HSV2RGB_FULL, 4);

	        return new Scalar(pointMatRgba.get(0, 0));
	    }	
}
